<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\ExchangeModel;
/**
 * Class RateController 汇率管理
 * @package app\admin\controller
 */
class RateController extends AdminBaseController
{
    public function index(){

        $data=  Db::name('rate')->select()->toArray();

        $this->assign('datas', $data );
        return $this->fetch();
    }




    
    public function del()
    {
        $id = $this->request->param('id', 0, 'intval');
        $result    = Db::name('rate')->where('id',$id)->delete();
        cache('all_rate',null);
        if ($result === false) {
            $this->error('删除失败，请重试！',url("rate/index"));
        }else{
            $this->success('删除成功！',url("rate/index"));
        }
    }


    function edit(){
        $id = input('param.id/d');
        if($id<=0){
            return $this->error('非法操作');
        }
        if(request()->isPost()){
            $usd_rate= trim(input('param.usd_rate/s'));
            if(empty($usd_rate)){
                return $this->error('汇率必须填写');
            }
            Db::name('rate')->where('id',$id)->update(['usd_rate'=>$usd_rate]);
            cache('all_rate',null);
            return $this->redirect('index');
        }
        $row = Db::name('rate')->where('id',$id)->find();
        $this->assign('action',url('rate/edit'));
        $this->assign('row',$row);
        return $this->fetch();
    }


    function ustd(){
        $row = Db::name('rate')->where('currency_symbol','USTD')->find();
        if($row && time()-$row['last_at']<600){
            return json(array('error'=>1,'msg'=>'10分钟之内不需要重复获取'));
        }
        $rs = \app\common\service\Ticker::getById();
        if($rs){
            if($row){
                Db::name('rate')->where('id',$row['id'])->update(['usd_rate'=>$rs['priceUsd'],'last_at'=>time()]);
            }else{
                Db::name('rate')
                    ->insert([
                        'currency_symbol'=>'USTD',
                        'usd_rate'       =>1/$rs['priceUsd'],
                        'last_at'        =>time(),
                        'name'           =>'Tether',
                        'currency_symbol_char' =>'',
                    ]);
            }
            cache('all_rate',null);
        }
        return json(array('error'=>0,'msg'=>'获取成功'));
    }
}